package cn.edu.bs.web.controller;

import cn.edu.bs.domain.Book;
import cn.edu.bs.domain.Type;
import cn.edu.bs.domain.User;
import cn.edu.bs.domain.UserExample;
import cn.edu.bs.service.BookService;
import cn.edu.bs.service.BorrowService;
import cn.edu.bs.service.TypeService;
import cn.edu.bs.service.UserService;
import cn.edu.bs.web.request.book.BookFormCommand;
import cn.edu.bs.web.request.user.UserFormCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author bs
 */
@Controller
@RequestMapping(value = {"/admin"})
public class BackController extends BaseController {

    private final String ADMIN_INDEX_PAGE = "admin/admin-index";
    private final String USER_LIST_PAGE = "admin/user/admin-users";
    private final String USER_ADD_PAGE = "admin/user/admin-users-add";
    private final String USER_EDIT_PAGE = "admin/user/admin-users-edit";
    private final String BOOK_LIST_PAGE = "admin/book/admin-books";
    private final String BOOK_ADD_PAGE = "admin/book/admin-books-add";
    private final String BOOK_EDIT_PAGE = "admin/book/admin-books-edit";

    private final UserService userService;
    private final BookService bookService;
    private final TypeService typeService;
    private final BorrowService borrowService;

    @Autowired
    public BackController(UserService userService, BookService bookService, TypeService typeService, BorrowService borrowService) {
        this.userService = userService;
        this.bookService = bookService;
        this.typeService = typeService;
        this.borrowService = borrowService;
    }


    @GetMapping("")
    public String index(Model model) {
        model.addAttribute("borrows", borrowService.transformCustomsToTOs(borrowService.selectBorrowList()));
        model.addAttribute("message", "hello, this is admin page! ");
        return ADMIN_INDEX_PAGE;
    }

    @GetMapping("/users")
    public String getAllUsers(Model model) {
        List<User> users = userService.selectByExample(null);
        model.addAttribute("users", users);
        return USER_LIST_PAGE;
    }

    @GetMapping("/users/add")
    public String toAddUserPage() {
        return USER_ADD_PAGE;
    }

    @PostMapping("/users/add")
    public String doAddUser(
            UserFormCommand command,
            Model model
    ) {
        String username = command.getUsername();
        String password = command.getPassword();

        if (username == null || username.trim().equals("")) {
            model.addAttribute("error", "用户名不能为空");
            return USER_ADD_PAGE;
        }
        if (password == null || password.trim().equals("")) {
            model.addAttribute("error", "密码不能为空");
            return USER_ADD_PAGE;
        }
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        if ("admin".equals(username) || userService.countByExample(example) != 0) {
            model.addAttribute("error", "用户名已存在");
            return USER_ADD_PAGE;
        }
        userService.insert(userService.transformCommandToEntity(command));
        model.addAttribute("success", "用户 " + username + " 添加成功");
        return USER_ADD_PAGE;
    }

    @GetMapping("/users/edit")
    public String toEditUserPage(
            @RequestParam(name = "id") Integer userId,
            Model model
    ) {
        User user = null;
        if (userId == null || (user = userService.selectByPrimaryKey(userId)) == null) {
            return "redirect:/admin/users";
        }
        model.addAttribute("user", user);
        return USER_EDIT_PAGE;
    }

    @PostMapping("/users/edit")
    public String doEditUser(
            User command,
            Model model
    ) {
        Integer userId = command.getUserId();
        String username = command.getUsername();
        String password = command.getPassword();

        if (userId == null) {
            model.addAttribute("error", "未找到用户");
            return USER_EDIT_PAGE;
        }

        if (username == null || username.trim().equals("")) {
            model.addAttribute("error", "用户名不能为空");
            return USER_EDIT_PAGE;
        }
        if (password == null || password.trim().equals("")) {
            model.addAttribute("error", "密码不能为空");
            return USER_EDIT_PAGE;
        }

        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        if ("admin".equals(username) || userService.countByExample(example) != 0) {
            model.addAttribute("error", "用户已存在");
            return USER_EDIT_PAGE;
        }
        userService.updateByPrimaryKey(command);
        return "redirect:/admin/users";
    }

    @GetMapping("/books")
    public String getAllBooks(Model model) {
        List<Book> books = bookService.selectByExample(null);
        model.addAttribute("books", books);
        return BOOK_LIST_PAGE;
    }

    @GetMapping("/books/add")
    public String toAddBookPage(
            Model model
    ) {
        List<Type> types = typeService.selectByExample(null);
        if (types != null) {
            model.addAttribute("types", types);
        }
        return BOOK_ADD_PAGE;
    }

    @PostMapping("/books/add")
    public String doAddBook(
            @Valid BookFormCommand bookFormCommand,
            Model model,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("error", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Type> types = typeService.selectByExample(null);
        if (types != null) {
            model.addAttribute("types", types);
        }
        Book book = bookService.transformCommandToEntity(bookFormCommand);
        bookService.insertSelective(book);
        model.addAttribute("success", " 添加成功");
        return BOOK_ADD_PAGE;
    }

    @GetMapping("/books/edit")
    public String toEditBooksPage(
            @RequestParam(name = "id") Integer bookId,
            Model model
    ) {
        Book book = null;
        if (bookId == null || (book = bookService.selectByPrimaryKey(bookId)) == null) {
            return "redirect:/admin/books";
        }
        List<Type> types = typeService.selectByExample(null);
        if (types != null) {
            model.addAttribute("types", types);
        }
        model.addAttribute("book", book);
        return BOOK_EDIT_PAGE;
    }

    @GetMapping("/books/delete")
    public String doDelete(
            @RequestParam(name = "id") Integer id,Model model
    ) {
        bookService.deleteByPrimaryKey(id);
        List<Book> books = bookService.selectByExample(null);
        model.addAttribute("books", books);
        return BOOK_LIST_PAGE;
    }

    @PostMapping("/books/edit")
    public String doEditBook(
            Book command
    ) {
        bookService.updateByPrimaryKey(command);
        return "redirect:/admin/books";
    }
}
